<template>
  <div class="pagination">
    <button
      :disabled="currentPageNo === 1"
      @click="$emit('changePage', currentPageNo - 1)"
    >
      上一页
    </button>
    <button v-show="startEnd.start > 1" @click="$emit('changePage', 1)">
      1
    </button>
    <button v-show="startEnd.start > 2">···</button>
    <!-- v-for在v-if之前执行 -->
    <button
      v-for="pageNo in startEnd.end"
      :key="pageNo"
      v-if="pageNo >= startEnd.start"
      :class="{ active: pageNo === currentPageNo }"
      @click="$emit('changePage', pageNo)"
    >
      {{ pageNo }}
    </button>
    <!-- <button>4</button>
    <button>5</button>
    <button>6</button>
    <button>7</button> -->

    <button v-show="startEnd.end < totalPages - 1">···</button>
    <button v-show="startEnd.end < totalPages" @click="$emit('changePage', totalPages)">{{ totalPages }}</button>

    <button
      :disabled="currentPageNo === totalPages"
      @click="$emit('changePage', currentPageNo + 1)"
    >
      下一页
    </button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  //接收数据
  props: {
    //当前页码
    currentPageNo: {
      type: Number,
      required: true,
    },
    //数据总条数
    total: {
      type: Number,
      default: 0,
    },
    //每页条数
    pageSize: {
      type: Number,
      required: true,
    },
    //连续分页个数
    continueNum: {
      type: Number,
      default: 5,
    },
  },

  computed: {
    //计算总页码
    totalPages() {
      return Math.ceil(this.total / this.pageSize);
    },

    //计算起始页和结束页
    startEnd() {
      let start = 0,
        end = 0;

      //如果连续页数大于总页数(极端情况)
      if (this.continueNum > this.totalPages) {
        start = this.currentPageNo;
        end = this.totalPages;
      } else {
        //普通情况
        start = this.currentPageNo - Math.floor(this.continueNum / 2);
        end = this.currentPageNo + Math.floor(this.continueNum / 2);

        //边界值判断
        if (start < 1) {
          start = 1;
          end = this.continueNum;
        }
        if (end > this.totalPages) {
          start = this.totalPages - this.continueNum + 1;
          end = this.totalPages;
        }
      }

      return {
        start,
        end,
      };
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
